<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button
            type='primary'
            @click="addUserVisible = true"
          >添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 添加角色弹窗框 -->
      <el-dialog
        title="添加角色"
        :visible.sync="addUserVisible"
        width="70%"
        @close="closeAddUserInfo"
      >
        <!-- 主体区域 -->
        <el-form
          :model="addUserForm"
          :rules="addUserFormRules"
          ref="addUser"
          label-width="100px"
        >
          <el-form-item
            label="角色名称"
            prop="roleName"
          >
            <el-input v-model="addUserForm.roleName"></el-input>
          </el-form-item>
          <el-form-item
            label="角色描述"
            prop="roleDesc"
          >
            <el-input v-model="addUserForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 尾部区域 -->
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="addUserVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="submitAddUserInfo"
          >确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑角色弹框 -->
      <el-dialog
        title="编辑角色"
        :visible.sync="alterUserVisible"
        width="70%"
        @close="alterAddUserInfo"
      >
        <!-- 主体区域 -->
        <el-form
          :model="alterUserForm"
          :rules="alterUserFormRules"
          ref="alterUser"
          label-width="100px"
        >
          <el-form-item
            label="角色名称"
            prop="roleName"
          >
            <el-input
              v-model="alterUserForm.roleName"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item
            label="角色描述"
            prop="roleDesc"
          >
            <el-input v-model="alterUserForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 尾部区域 -->
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="alterUserVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="submitAlterUserInfo"
          >确 定</el-button>
        </span>
      </el-dialog>

      <!-- 角色表格列表 -->
      <el-table
        :data="roleList"
        stripe
        style="width: 100%"
        border
      >
        <!-- 展开行 -->
        <el-table-column type='expand'>
          <template slot-scope="scope">

            <el-row
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom',i1 === 0 ? 'bdtop':'','vcenter']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close='removeRightById(scope.row,item1.id)'
                >{{item1.authName}}</el-tag>
                <i class='el-icon-arrow-right'></i>
              </el-col>
              <!-- 渲染二级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2,i2) in item1.children"
                  :key="i2"
                  :class="[i2 !== 0 ?'bdtop':'','vcenter']"
                >
                  <!-- 二级权限 -->
                  <el-col :span='6'>
                    <el-tag
                      type='success'
                      closable
                      @close='removeRightById(scope.row,item2.id)'
                    >{{item2.authName}}</el-tag>
                    <i class='el-icon-arrow-right'></i>

                  </el-col>
                  <el-col :span='18'>
                    <el-tag
                      v-for="(item3,i3) in item2.children"
                      :key="i3"
                      closable
                      type='warning'
                      @close='removeRightById(scope.row,item3.id)'
                    >
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type='index'></el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称"
        ></el-table-column>
        <el-table-column
          prop="roleDesc"
          label="角色描述"
        ></el-table-column>
        <el-table-column label="操作">
          <template slot-scope='scope'>
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row)"
            >编辑</el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row)"
            >删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="giveRight(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限按钮弹出框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="rightVisible"
      width="70%"
      @close='setRight'
    >
      <el-tree
        :data="nodeList"
        :props="roleListProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys='checkedList'
        ref='treeRef'
      ></el-tree>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="rightVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="givePeopleRigth"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 权限列表
      roleList: [],
      // 所有权限的节点树
      nodeList: [],
      // 已选中的节点列表
      checkedList: [],
      // 展开节点的权限设置
      roleListProps: {
        children: 'children',
        label: 'authName'
      },
      // 分配权限弹窗
      rightVisible: false,
      //  即将分配权限的id
      roleId: '',
      // 添加角色
      addUserVisible: false,
      addUserForm: {
        roleName: '',
        roleDesc: ''
      },
      addUserFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 编辑角色
      alterUserVisible: false,
      alterUserForm: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      },
      alterUserFormRules: {
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { data: result } = await this.$http.get('roles')
      console.log(result)
      if (result.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.roleList = result.data
      console.log(this.roleList)
    },

    // 移除权限通过id
    async removeRightById(scope, rightId) {
      const confirm = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(confirm)
      if (confirm !== 'confirm') return this.$message.info('用户取消删除')
      const { data: result } = await this.$http.delete(`roles/${scope.id}/rights/${rightId}`)
      if (result.meta.status !== 200) return this.$message.error('删除权限失败')
      console.log(result.data)
      scope.children = result.data
    },
    // 按钮点击分配权限
    async giveRight(role) {
      this.roleId = role.id
      const { data: result } = await this.$http.get('rights/tree')
      if (result.meta.status !== 200) return this.$message.error('获取权限失败')
      this.nodeList = result.data
      // 递归获取节点
      this.getCheckedList(role, this.checkedList)
      this.rightVisible = true
    },
    // 通过递归过滤已选择的权限id
    getCheckedList(node, arr) {
      // 如果当前node的节点不包含children 属性就是第三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getCheckedList(item, arr)
      })
    },
    // 关闭对话框 置空已选择的id
    setRight() {
      this.checkedList = []
    },
    // 赋予权限
    async givePeopleRigth() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()

      ]
      const idStr = keys.join(',')
      const { data: result } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (result.meta.status !== 200) return this.$message.error('分配权限失败')
      this.$message.success('分配权限成功')
      this.getRoleList()
      this.rightVisible = false
    },
    closeAddUserInfo() {
      this.$refs.addUser.resetFields()
      this.addUserForm.roleName = ''
      this.addUserForm.desc = ''
      this.addUserVisible = false
    },
    // 提添加角色的信息
    async submitAddUserInfo() {
      this.$refs.addUser.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('请检查已填写的信息')
        }
        const { data: result } = await this.$http.post('roles', this.addUserForm)
        if (result.meta.status !== 201) return this.$message.error('添加角色失败')
        this.$message.success('添加角色成功')
        this.addUserVisible = false
        this.getRoleList()
      })
    },
    // 编辑按钮点击
    async showEditDialog(row) {
      this.alterUserVisible = true
      const { data: result } = await this.$http.get(`roles/${row.id}`)
      if (result.meta.status !== 200) return this.$message.error('查询角色失败')
      this.alterUserForm = result.data
      console.log(this.alterUserForm)
    },
    alterAddUserInfo() {
      this.$refs.alterUser.resetFields()
      this.alterUserForm.roleName = ''
      this.alterUserForm.roleDesc = ''
      this.alterUserForm.roleId = ''

      this.alterUserVisible = false
    },
    async submitAlterUserInfo() {
      this.$refs.alterUser.validate(async (valid) => {
        if (!valid) return this.$message.error('请检查已填写信息')
        const { data: result } = await this.$http.put(`roles/${this.alterUserForm.roleId}`,
          { roleName: this.alterUserForm.roleName, roleDesc: this.alterUserForm.roleDesc })
        if (result.meta.status !== 200) return this.$message.error('更新角色信息失败')
        this.$message.success('修改用户信息成功')
        this.alterUserVisible = false

        this.getRoleList()
      })
    },
    // 删除提示框
    async deleteUser(row) {
      const confirm = await this.$confirm(`此操作将永久删除该角色 ${row.roleName}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(confirm)
      if (confirm !== 'confirm') return this.$message.info('用户取消删除')
      const { data: result } = await this.$http.delete(`roles/${row.id}`)
      if (result.meta.status !== 200) return this.$message.error('删除角色失败')
      this.$message.success('删除角色成功')
      this.getRoleList()
    }

  }
}
</script>
<style lang="less" scoped>
.el-tag{
  margin:7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;

}
.vcenter {
  display: flex;
  align-items:center
}
</style>
